﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using Extention;

namespace DataAccess
{
    public class ListExCommand<T>
    {
        public delegate T GenericMapperDelegate(ListEx<GenericDataObject> list);

        private GenericMapperDelegate genericMapper;
        protected ICommand command;

        public ListExCommand()
        {
        }
        public ListExCommand(ICommand command)
        {
            this.command = command;
        }

        public ListExCommand<T> Map(GenericMapperDelegate genericMapper)
        {
            this.genericMapper = genericMapper;
            return this;
        }
        public ListEx<T> ToListEx()
        {
            var result = new ListEx<T>();
            using (ListEx<GenericDataObject> reader = 
                (ListEx<GenericDataObject>)command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                reader.Fill();
                var myReader = reader;
                while (reader.Read())
                {
                    T context = genericMapper.Invoke(myReader);
                    result.Add(context);
                }
            }
            return result;
        }
    }
    public class ListExAutoMap<TResult,TSource>
    {
        public delegate TResult GenericEnumMapperDelegate(TSource list);

        private GenericEnumMapperDelegate genericMapper;
        protected IEnumerable<TSource> objectToMap;

        public ListExAutoMap()
        {
        }
        public ListExAutoMap(IEnumerable<TSource> objectToMap)
        {
            this.objectToMap = objectToMap;
        }

        public ListExAutoMap<TResult, TSource> Map(GenericEnumMapperDelegate genericMapper)
        {
            this.genericMapper = genericMapper;
            return this;
        }        
        public ListEx<TResult> ToListEx()
        {
            var result = new ListEx<TResult>();

            IEnumerator<TSource> t =
                objectToMap.GetEnumerator();
          
            while (t.MoveNext())
            {
                var myReader = t.Current;
                TResult context = genericMapper.Invoke(myReader);
                result.Add(context);                
            }
            
            return result;
        }
    }
}
